//
//  SJAddWordViewController.m
//  WSL
//
//  Created by CJ on 2017/11/27.
//  Copyright © 2017年 sanjuetech. All rights reserved.
//

#import "SJAddWordViewController.h"
#import "SJAddWHCell.h"
#import "SJAddItem.h"
#import "SJWordItem.h"
#import "SJAddMediaApi.h"
#import "SJAddWordApi.h"

@interface SJAddWordViewController () <UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, strong) UIView *navigationBarView; // 背景
@property (nonatomic, strong) UIScrollView *containView;
@property (nonatomic, strong) UIView *inputBGView;
@property (nonatomic, strong) UITextField *inputTextView;
@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, copy) NSString *selectedWidth;
@property (nonatomic, copy) NSString *selectedHeight;

@property (strong, nonatomic) UIButton *cpButton;
@property (nonatomic, copy) NSString *allowCopy; // 1 不允许, 2 允许

@property (strong, nonatomic) UIView *arrowView;
@property (nonatomic, copy) NSString *selectedArrow;

@property (strong, nonatomic) UIButton *topArrowButton;
@property (strong, nonatomic) UIButton *bottomArrowButton;
@property (strong, nonatomic) UIButton *rightArrowButton;
@property (strong, nonatomic) UIButton *leftArrowButton;
@property (nonatomic, strong) NSMutableArray *arrowArray;

@end

@implementation SJAddWordViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [SJStatisticTool beginLogPageView:NSStringFromClass([self class])];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [SJStatisticTool endLogPageView:NSStringFromClass([self class])];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    if (![SJGuideView shouldShowGuider:@"addType"]) {
        return;
    }
    
    NSString *imageName = @"guide_entry_size";
    if (812 == SJScreenH) {
        imageName = [NSString stringWithFormat:@"%@-x", imageName];
    }
    
    if ([SJGuideView shouldShowGuider:imageName]) {
        [SJGuideView guideViewWithImageName:imageName];
    }
}

- (void)dealloc {
    SJLogFunc;
    [self removeObserver:self forKeyPath:@"selectedHeight" context:nil];
    [self removeObserver:self forKeyPath:@"selectedWidth" context:nil];
    [self removeObserver:self forKeyPath:@"selectedArrow" context:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setupUI];
//    [self.inputTextView becomeFirstResponder];
    
    self.allowCopy = @"2";
    self.selectedHeight = @"1";
    self.selectedWidth = @"2";

    [self filterData:self.selectedHeight];
    
    [self addObserver:self forKeyPath:@"selectedWidth" options:NSKeyValueObservingOptionNew context:nil];
    [self addObserver:self forKeyPath:@"selectedHeight" options:NSKeyValueObservingOptionNew context:nil];
    [self addObserver:self forKeyPath:@"selectedArrow" options:NSKeyValueObservingOptionNew context:nil];
    self.selectedArrow = @"0";
}

- (void)filterData:(NSString *)h {
    
    SJAddItem *item_0 = self.dataArray[0];
    SJAddItem *item_1 = self.dataArray[1];
    SJAddItem *item_2 = self.dataArray[2];
    SJAddItem *item_3 = self.dataArray[3];
    
    item_0.state = @"2";
    
    for (NSMutableDictionary *dict in self.optionArray) {
        
        if ([dict[@"h"] isEqualToString:@"1"] && [dict[@"w"] isEqualToString:@"4"]) {  // 0.5:2
            item_1.state = @"1";
            break;
        } else {
            item_1.state = @"0";
        }
    }
    
    for (NSMutableDictionary *dict in self.optionArray) {
        
        if ([dict[@"h"] isEqualToString:@"1"] && [dict[@"w"] isEqualToString:@"6"]) {  // 0.5:3
            item_2.state = @"1";
            break;
        } else {
            item_2.state = @"0";
        }
    }
    
    for (NSMutableDictionary *dict in self.optionArray) {
        
        if ([dict[@"h"] isEqualToString:@"1"] && [dict[@"w"] isEqualToString:@"8"]) {  // 0.5:4
            item_3.state = @"1";
            break;
        } else {
            item_3.state = @"0";
        }
    }
    
}

/** 添加观察者必须要实现的方法 */
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    
    NSString *new = [change objectForKey:@"new"];
    
    if ([keyPath isEqualToString:@"selectedWidth"]) {
        
        [self changeInputWidth:new];
        
    } else if ([keyPath isEqualToString:@"selectedHeight"]) {
        
        [self changeInputHeight:new];
        
    } else if ([keyPath isEqualToString:@"selectedArrow"]) {
        
        [self changeArrow:new];
        
    }
}

- (void)changeArrow:(NSString *)new {
    
    int orNum = [new intValue];
    
    for (UIButton *btn in self.arrowArray) {
        
        if (btn.tag & orNum) {
            btn.hidden = NO;
        } else {
            btn.hidden = YES;
        }
    }
}

- (void)changeInputWidth:(NSString *)new {
    
    CGFloat w = [new intValue] * SJItemWH + ([new intValue] - 1) * SJMargin;
    
    // 开启动画
    [UIView animateWithDuration:.25 animations:^{
        self.inputBGView.sd_layout
        .widthIs(w);
        [self.inputTextView updateLayout];
        [self.inputBGView updateLayout];
        [self.topArrowButton updateLayout];
        [self.rightArrowButton updateLayout];
        [self.bottomArrowButton updateLayout];
        [self.leftArrowButton updateLayout];
    }];
}

- (void)changeInputHeight:(NSString *)new {
    
    CGFloat h = [new intValue] * SJItemWH + ([new intValue] - 1) * SJMargin;
    
    // 开启动画
    [UIView animateWithDuration:.25 animations:^{
        self.inputBGView.sd_layout
        .heightIs(h);
        [self.inputTextView updateLayout];
        [self.inputBGView updateLayout];
        [self.topArrowButton updateLayout];
        [self.rightArrowButton updateLayout];
        [self.bottomArrowButton updateLayout];
        [self.leftArrowButton updateLayout];
    }];
    
}

- (void)setupUI {

    [self.view addSubview:self.navigationBarView];
    
    if (812 == SJScreenH) {
        self.navigationBarView.sd_layout
        .leftSpaceToView(self.view, SJLayoutFrame(0))
        .topSpaceToView(self.view, SJLayoutFrame(40))
        .heightIs(SJLayoutFrame(50))
        .widthIs(SJScreenW);
    } else {
        self.navigationBarView.sd_layout
        .leftSpaceToView(self.view, SJLayoutFrame(0))
        .topSpaceToView(self.view, SJLayoutFrame(0))
        .heightIs(SJLayoutFrame(50))
        .widthIs(SJScreenW);
    }
    
    [self.view addSubview:self.containView];
    self.containView.sd_layout
    .leftSpaceToView(self.view, SJLayoutFrame(0))
    .topSpaceToView(self.navigationBarView, SJLayoutFrame(0))
    .rightSpaceToView(self.view, SJLayoutFrame(0))
    .bottomSpaceToView(self.view, SJLayoutFrame(0));
    
    // 输入框，默认4*1
    CGFloat h = SJItemWH;
    CGFloat w = SJItemWH * 2 + SJMargin * 1;
    
    [self.containView addSubview:self.inputBGView];
    self.inputBGView.sd_layout
    .centerXEqualToView(self.containView)
    .topSpaceToView(self.containView, SJLayoutFrame(33))
    .heightIs(h)
    .widthIs(w);
    
    [self.inputBGView addSubview:self.inputTextView];
    self.inputTextView.sd_layout.spaceToSuperView(UIEdgeInsetsMake(SJLayoutFrame(3), SJLayoutFrame(3), SJLayoutFrame(3), SJLayoutFrame(3)));
    
    // 箭头
    
    // 上
    [self.containView addSubview:self.topArrowButton];
    self.topArrowButton.sd_layout
    .bottomSpaceToView(self.inputBGView, 0)
    .centerXEqualToView(self.inputBGView)
    .heightIs(SJMargin)
    .widthIs(SJMargin);
    
    // 下
    [self.containView addSubview:self.bottomArrowButton];
    self.bottomArrowButton.sd_layout
    .topSpaceToView(self.inputBGView, 0)
    .centerXEqualToView(self.inputBGView)
    .heightIs(SJMargin)
    .widthIs(SJMargin);
    
    // 左
    [self.containView addSubview:self.leftArrowButton];
    self.leftArrowButton.sd_layout
    .rightSpaceToView(self.inputBGView, 0)
    .centerYEqualToView(self.inputBGView)
    .heightIs(SJMargin)
    .widthIs(SJMargin);
    
    // 右
    [self.containView addSubview:self.rightArrowButton];
    self.rightArrowButton.sd_layout
    .leftSpaceToView(self.inputBGView, 0)
    .centerYEqualToView(self.inputBGView)
    .heightIs(SJMargin)
    .widthIs(SJMargin);
    
    
    [self.containView addSubview:self.collectionView];
    self.collectionView.sd_layout
    .leftSpaceToView(self.containView, SJLayoutFrame(20))
    .topSpaceToView(self.inputBGView, SJLayoutFrame(43))
    .heightIs(SJLayoutFrame(22))
    .widthIs(SJScreenW - SJLayoutFrame(40));
    
    [self.containView addSubview:self.arrowView];
    self.arrowView.sd_layout
    .leftSpaceToView(self.containView, SJLayoutFrame(20))
    .topSpaceToView(self.collectionView, SJLayoutFrame(25))
    .heightIs(SJLayoutFrame(30))
    .widthIs(SJLayoutFrame(30) * 4 + SJLayoutFrame(10) * 3);
    
    // 解释说明
    
    UILabel *explain = [UILabel new];
    explain.textColor = SJColorHexString(@"#ffffff");
    explain.font = [UIFont systemFontOfSize:SJLayoutFrame(13)];
    explain.textAlignment = NSTextAlignmentJustified;
    explain.alpha = .6;
    explain.text = @"1、可输入21个字符（中文、符号、空格、英文都算一个字符，不支持换行和回车符号）\n\n2、可输入符号“ .” 下点 “•” 中点 “( )” 括号 “&”和号 “ –”横杠 “:”冒号";
    explain.numberOfLines = 0;
    
    [self.containView addSubview:explain];
    explain.sd_layout
    .centerXEqualToView(self.containView)
    .topSpaceToView(self.arrowView, SJLayoutFrame(30))
    .autoHeightRatio(0)
    .widthIs(SJScreenW - SJLayoutFrame(40));
    
    
    
    UILabel *cpLabel = [UILabel new];
    cpLabel.textColor = SJColorHexString(@"#ffffff");
    cpLabel.font = [UIFont systemFontOfSize:SJLayoutFrame(12)];
    cpLabel.textAlignment = NSTextAlignmentCenter;
    cpLabel.text = @"允许复制";
    cpLabel.numberOfLines = 1;
    
    [self.view addSubview:cpLabel];
    cpLabel.sd_layout
    .rightSpaceToView(self.view, SJLayoutFrame(26))
    .bottomSpaceToView(self.view, SJLayoutFrame(26.5))
    .heightIs(SJLayoutFrame(20));
    [cpLabel setSingleLineAutoResizeWithMaxWidth:180];
    
    [self.view addSubview:self.cpButton];
    self.cpButton.sd_layout
    .rightSpaceToView(cpLabel, SJLayoutFrame(0))
    .centerYEqualToView(cpLabel)
    .heightIs(SJLayoutFrame(30))
    .widthIs(SJLayoutFrame(30));
    
    // scrollview自动contentsize
    [self.containView setupAutoContentSizeWithBottomView:self.arrowView bottomMargin:0];
    
}


#pragma mark - setter


- (NSMutableArray *)arrowArray {
    
    if (!_arrowArray) {
        
        _arrowArray = [[NSMutableArray alloc] init];
        
    }
    return _arrowArray;
}

- (UIButton *)topArrowButton{
    
    if (!_topArrowButton) {
        _topArrowButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_topArrowButton setImage:[UIImage imageNamed:@"btn_up_icon"] forState:UIControlStateNormal];
        _topArrowButton.tag = 1;
        [self.arrowArray addObject:_topArrowButton];
    }
    return _topArrowButton;
}

- (UIButton *)rightArrowButton{
    
    if (!_rightArrowButton) {
        _rightArrowButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_rightArrowButton setImage:[UIImage imageNamed:@"btn_right_icon"] forState:UIControlStateNormal];
        _rightArrowButton.tag = 2;
        [self.arrowArray addObject:_rightArrowButton];
    }
    return _rightArrowButton;
}

- (UIButton *)bottomArrowButton{
    
    if (!_bottomArrowButton) {
        _bottomArrowButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_bottomArrowButton setImage:[UIImage imageNamed:@"btn_down_icon"] forState:UIControlStateNormal];
        _bottomArrowButton.tag = 4;
        [self.arrowArray addObject:_bottomArrowButton];
    }
    return _bottomArrowButton;
}

- (UIButton *)leftArrowButton{
    
    if (!_leftArrowButton) {
        _leftArrowButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_leftArrowButton setImage:[UIImage imageNamed:@"btn_left_icon"] forState:UIControlStateNormal];
        _leftArrowButton.tag = 8;
        [self.arrowArray addObject:_leftArrowButton];
    }
    return _leftArrowButton;
}



- (void)arrowAction:(UIButton *)button {
    
    button.selected = !button.selected;
    
    int orNum = 0;
    
    for (UIButton *btn in self.arrowView.subviews) {
        
        if (btn.selected) {
            orNum |= btn.tag;
        }
    }
    
    self.selectedArrow = [NSString stringWithFormat:@"%d", orNum];
}

- (UIView *)arrowView {
    
    if (!_arrowView) {
        
        _arrowView = [UIView new];
        
        UIButton *top = [UIButton buttonWithType:UIButtonTypeCustom];
        [top setImage:[UIImage imageNamed:@"addtext_icon_top_nor"] forState:UIControlStateNormal];
        [top setImage:[UIImage imageNamed:@"addtext_icon_top_sel"] forState:UIControlStateSelected];
        [top addTarget:self action:@selector(arrowAction:) forControlEvents:UIControlEventTouchUpInside];
        top.tag = 1;
        [_arrowView addSubview:top];
        
        UIButton *right = [UIButton buttonWithType:UIButtonTypeCustom];
        [right setImage:[UIImage imageNamed:@"addtext_icon_right_nor"] forState:UIControlStateNormal];
        [right setImage:[UIImage imageNamed:@"addtext_icon_right_sel"] forState:UIControlStateSelected];
        [right addTarget:self action:@selector(arrowAction:) forControlEvents:UIControlEventTouchUpInside];
        right.tag = 2;
        [_arrowView addSubview:right];
        
        UIButton *bottom = [UIButton buttonWithType:UIButtonTypeCustom];
        [bottom setImage:[UIImage imageNamed:@"addtext_icon_botton_nor"] forState:UIControlStateNormal];
        [bottom setImage:[UIImage imageNamed:@"addtext_icon_botton_sel"] forState:UIControlStateSelected];
        [bottom addTarget:self action:@selector(arrowAction:) forControlEvents:UIControlEventTouchUpInside];
        bottom.tag = 4;
        [_arrowView addSubview:bottom];
        
        UIButton *left = [UIButton buttonWithType:UIButtonTypeCustom];
        [left setImage:[UIImage imageNamed:@"addtext_icon_left_nor"] forState:UIControlStateNormal];
        [left setImage:[UIImage imageNamed:@"addtext_icon_left_sel"] forState:UIControlStateSelected];
        [left addTarget:self action:@selector(arrowAction:) forControlEvents:UIControlEventTouchUpInside];
        left.tag = 8;
        [_arrowView addSubview:left];
        
        top.sd_layout.heightIs(SJLayoutFrame(25));
        right.sd_layout.heightIs(SJLayoutFrame(25));
        bottom.sd_layout.heightIs(SJLayoutFrame(25));
        left.sd_layout.heightIs(SJLayoutFrame(25));
        
        NSMutableArray *temp = [NSMutableArray new];
        [temp addObject:top];
        [temp addObject:right];
        [temp addObject:bottom];
        [temp addObject:left];
        
        [_arrowView setupAutoMarginFlowItems:[temp copy] withPerRowItemsCount:temp.count itemWidth:SJLayoutFrame(25) verticalMargin:0 verticalEdgeInset:0 horizontalEdgeInset:0];
        
        
    }
    return _arrowView;
}


#pragma mark - getter

- (void)allowCopyAction {
    
    self.cpButton.selected = !self.cpButton.selected;
    if (self.cpButton.selected) {
        self.allowCopy = @"2";
    } else {
        self.allowCopy = @"1";
    }
}

- (UIButton *)cpButton {
    
    if (!_cpButton) {
        
        _cpButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_cpButton setImage:[UIImage imageNamed:@"btn_allow_collect_nor"] forState:UIControlStateNormal];
        [_cpButton setImage:[UIImage imageNamed:@"btn_allow_collect_sel"] forState:UIControlStateSelected];
        [_cpButton addTarget:self action:@selector(allowCopyAction) forControlEvents:UIControlEventTouchUpInside];
        _cpButton.selected = YES;
    }
    return _cpButton;
}

- (NSMutableArray *)dataArray {
    
    if (!_dataArray) {
        
        _dataArray = [[NSMutableArray alloc] init];
        for (int i = 0; i < 4; i++) {
            
            SJAddItem *item = [SJAddItem new];
            
            if (0 == i) item.numble = @"1";
            if (1 == i) item.numble = @"2";
            if (2 == i) item.numble = @"3";
            if (3 == i) item.numble = @"4";
            
            item.state = @"1";
            [_dataArray addObject:item];
        }
    }
    return _dataArray;
}

- (UIView *)navigationBarView{
    
    if (!_navigationBarView) {
        
        _navigationBarView = [UIView new];
        _navigationBarView.backgroundColor = [UIColor clearColor];
        
        UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapAction)];
        singleTap.cancelsTouchesInView = NO;
        [_navigationBarView addGestureRecognizer:singleTap];
        
        // 返回
        UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [backButton setImage:[UIImage imageNamed:@"addtext-icon-return"] forState:UIControlStateNormal];
        [backButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
        
        [_navigationBarView addSubview:backButton];
        backButton.sd_layout
        .centerYEqualToView(_navigationBarView)
        .leftSpaceToView(_navigationBarView, SJLayoutFrame(10))
        .heightIs(SJLayoutFrame(30))
        .widthIs(SJLayoutFrame(30));
        
        // 词条输入
        UILabel *wordLabel = [UILabel new];
        wordLabel.textColor = SJColorHexString(@"#ffffff");
        wordLabel.font = [UIFont fontWithName:@"Helvetica" size:SJLayoutFrame(17)];
        wordLabel.textAlignment = NSTextAlignmentCenter;
        wordLabel.text = @"添加词条";
        
        [_navigationBarView addSubview:wordLabel];
        wordLabel.sd_layout
        .centerYEqualToView(_navigationBarView)
        .centerXEqualToView(_navigationBarView)
        .heightIs(SJLayoutFrame(27));
        [wordLabel setSingleLineAutoResizeWithMaxWidth:SJScreenW * .5];
        
        // 确定
        UIButton *affirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [affirmButton setImage:[UIImage imageNamed:@"addtext_icon_confirm"] forState:UIControlStateNormal];
        [affirmButton addTarget:self action:@selector(affirmAction) forControlEvents:UIControlEventTouchUpInside];
        
        [_navigationBarView addSubview:affirmButton];
        affirmButton.sd_layout
        .centerYEqualToView(_navigationBarView)
        .rightSpaceToView(_navigationBarView, SJLayoutFrame(20))
        .heightIs(SJLayoutFrame(30))
        .widthIs(SJLayoutFrame(60));
        
    }
    return _navigationBarView;
}

- (BOOL)isValidateWord:(NSString *)word {
    
    NSPredicate *wordTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", @"^[\\w|\u4E00-\u9FA5|(|)|:|&|-|·|.]*$"];
    
    return [wordTest evaluateWithObject:word];
    
}

- (void)affirmAction {
    
    if (!self.selectedWidth) {
        
        [SVProgressHUD showInfoWithStatus:@"请选择尺寸"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }
    
    if (![self.inputTextView.text isNotBlank]) { // 插入空
        
        [self insertBlank];
        return;
    }
    
    if ([self.inputTextView.text length] > 21) { // 最多21个字
        [SVProgressHUD showInfoWithStatus:@"最多21个字符"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }
    
    if (![self isValidateWord:self.inputTextView.text]) {
        [SVProgressHUD showInfoWithStatus:@"字符不合法"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }
    
    // 1.拼接参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
    parameters[@"pid"] = self.item?self.item.bid:@"0";
    parameters[@"key"] = self.inputTextView.text;
    parameters[@"l"] = self.l;
    parameters[@"t"] = self.t;
    parameters[@"w"] = self.selectedWidth;
    parameters[@"h"] = self.selectedHeight;
    parameters[@"can_fav"] = self.allowCopy;
    parameters[@"arrow"] = self.selectedArrow;
    
    SJAddWordApi *api = [[SJAddWordApi alloc] initWithParameters:parameters];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            
            SJWordItem *item = [SJWordItem modelWithJSON:api.responseObject[@"content"]];
            item.is_me = @"1";
            
            if (self.item) {
                [[NSNotificationCenter defaultCenter] postNotificationName:SJDidAddOneWordNotification object:nil userInfo:@{@"item": item}];
            } else {
                [[NSNotificationCenter defaultCenter] postNotificationName:SJDidAddZeroWordNotification object:nil userInfo:@{@"item": item}];
            }
            
            [self.navigationController popViewControllerAnimated:YES];
        } else {
            
            NSString *msg = api.responseObject[@"result"][@"msg"];
            [SVProgressHUD showErrorWithStatus:msg];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
        }
        
    } failure:^(YTKBaseRequest *request) {
        
    }];
}

- (void)insertBlank {
    
    // 1.拼接参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
    parameters[@"pid"] = self.item?self.item.bid:@"0";
    parameters[@"format"] = @"8";
    parameters[@"l"] = self.l;
    parameters[@"t"] = self.t;
    parameters[@"w"] = self.selectedWidth;
    parameters[@"h"] = self.selectedHeight;
    parameters[@"can_fav"] = self.allowCopy;
    parameters[@"arrow"] = self.selectedArrow;
    
    SJAddMediaApi *api = [[SJAddMediaApi alloc] initWithParameters:parameters];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            
            SJWordItem *item = [SJWordItem modelWithJSON:api.responseObject[@"content"]];
            
            if (self.item) {
                [[NSNotificationCenter defaultCenter] postNotificationName:SJDidAddOneWordNotification object:nil userInfo:@{@"item": item}];
            } else {
                [[NSNotificationCenter defaultCenter] postNotificationName:SJDidAddZeroWordNotification object:nil userInfo:@{@"item": item}];
            }
            
            [self.navigationController popViewControllerAnimated:YES];
        }
        
    } failure:^(YTKBaseRequest *request) {
        
    }];
}

- (void)backAction {
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (UITextField *)inputTextView {
    
    if (!_inputTextView) {
        
        _inputTextView = [UITextField new];
        _inputTextView.font = [UIFont fontWithName:@"Helvetica-Bold" size:SJLayoutFrame(16)];
        _inputTextView.textColor = SJColorHexString(@"#ffffff");
        _inputTextView.backgroundColor = [UIColor clearColor];
        _inputTextView.textAlignment = NSTextAlignmentCenter;
        _inputTextView.returnKeyType = UIReturnKeyDone;
        
        NSString *holderText = @"请输入...";
        NSMutableAttributedString *placeholder = [[NSMutableAttributedString alloc]initWithString:holderText];
        [placeholder addAttribute:NSForegroundColorAttributeName
                            value:SJColorHexString(@"#ffffff90")
                            range:NSMakeRange(0, holderText.length)];
        [placeholder addAttribute:NSFontAttributeName
                            value:[UIFont systemFontOfSize:SJLayoutFrame(15)]
                            range:NSMakeRange(0, holderText.length)];
        _inputTextView.attributedPlaceholder = placeholder;
        
    }
    return _inputTextView;
}

- (UIView *)inputBGView {
    
    if (!_inputBGView) {
        
        _inputBGView = [UIView new];
        _inputBGView.sd_cornerRadius = @(SJCornerRadius);
        _inputBGView.backgroundColor = SJColorHexString(@"#ffffff19");
    }
    return _inputBGView;
}

- (UIScrollView *)containView {
    
    if (!_containView) {
        
        _containView = [UIScrollView new];
        
        UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapAction)];
        singleTap.cancelsTouchesInView = NO;
        [_containView addGestureRecognizer:singleTap];
        
    }
    return _containView;
}

- (void)singleTapAction {
    
    [self.view endEditing:YES];
}


- (UICollectionView *)collectionView {
    
    if (!_collectionView) {
        
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        CGFloat h = SJLayoutFrame(22);
        CGFloat w = SJLayoutFrame(52);
        layout.minimumInteritemSpacing = SJLayoutFrame(40);
        layout.minimumLineSpacing = SJLayoutFrame(20);
        layout.itemSize = CGSizeMake(w, h);
        
        _collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor clearColor];
        
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        
        [_collectionView registerClass:[SJAddWHCell class] forCellWithReuseIdentifier:NSStringFromClass([SJAddWHCell class])];
        
    }
    
    return _collectionView;
}

#pragma mark - UICollectionViewDataSource, UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.dataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    SJAddWHCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([SJAddWHCell class]) forIndexPath:indexPath];
    SJAddItem *item = self.dataArray[indexPath.item];
    cell.item = item;
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    for (SJAddItem *item in self.dataArray) {
        if ([item.state isEqualToString:@"2"]) {
            item.state = @"1";
        }
    }
    
    SJAddItem *item = self.dataArray[indexPath.item];
    if ([item.state isEqualToString:@"0"]) {
        return;
    }
    item.state = @"2";
    [self.collectionView reloadData];
    
    self.selectedWidth = [NSString stringWithFormat:@"%ld", [item.numble integerValue] * 2];
}

@end

